import { createApp } from 'vue'
// import Loding from './loading.vue'
import { addClass, removeClass } from '@/assets/js/dom'
const relativeCls = 'g-relative'
export default function createLoadingLikeDireactive(Comp) {
  return {
    mounted(el, binding) {
      const app = createApp(Comp)
      const instance = app.mount(document.createElement('div'))
      const name = Comp.name // 区分每个组件 混乱
      if (!el[name]) {
        el[name] = {}
      }
      el[name].instance = instance // 技巧在所以生命函数中都能拿的参数了
      const title = binding.arg // 接收自定义指令传过来的参数
      if (typeof title !== 'undefined') {
        instance.setTitle(title) // loading组件中改赋值
      }
      if (binding.value) { // 指令传参有值的情况下
        append(el)
      }
    },
    updated(el, binding) {
      const title = binding.arg
      const name = Comp.name
      if (typeof title !== 'undefined') {
        el[name].instance.setTitle(title)
      }
      if (binding.value !== binding.oldValue) { // 判断自定义指令传参值是否为true 前后值是否一致
        binding.value ? append(el) : removes(el)
      }
    }
  }
  function append(el) { // 挂载Dom
    const style = getComputedStyle(el)
    const name = Comp.name
    // 此处判断挂载的Dom是否有定位 没有就添加
    // debugger
    if (['absolute', 'fixed', 'relative'].indexOf(style.position === -1)) {
      addClass(el, relativeCls) // 添加class名
    }
    el.appendChild(el[name].instance.$el) // 把loding组件挂载到el调用指令的Dom中
  }
  function removes(el) {
    const name = Comp.name
    removeClass(el, relativeCls)
    el.removeChild(el[name].instance.$el)
  }
}
